﻿

var updateRuleUrl = ArrangeUrl + "/DoctorScheduling/update";
var queryTpRuleUrl = ArrangeUrl + "/DoctorScheduling/getScheduling";
var saveBzPbRuleUrl = ArrangeUrl + "/scheduling/save";
var mqueryDeptListUrl = TriageUrl + "/Triage/getDeptList";
var schedulingdicListUrl = SystemLimitUrl + "/dic/list";//排班字典-列表
var m_operType = "";
var schedulingdicList = [];//排班字典接口获取data数据


$(function () {

    initP_P_Switch();
    var _tabIndex = GetQueryString("index");
    if (_tabIndex != "" && _tabIndex != null) {
        $('#mytab a:eq(' + _tabIndex + ')').tab('show');
        loadDisplayRuleTable();
        $("#span_dept").hide();
        changeOperate(_tabIndex);
    }
    else {
        //$("#tab_terminal").Huitab();
        changeOperate(0);
    }

    mloadDept("dept_infolist");
    $('#mytab a:eq(0)').tab('show');

    $("#dept_name_index").html(unescape(getCookie("deptName")?getCookie("deptName"):''));
    $("#name_index").html(unescape(getCookie("name")?getCookie("name"):''));
});


function initP_P_Switch() {

    $("[name='switch_p_or_p']").bootstrapSwitch({
        onText: "分诊",
        offText: "排班",
        size: "small",
        animate: false,
        onColor: "primary",
        offColor: "primary",
        onSwitchChange: function (e, s) {
            if (s) {
                console.log("切换到分诊");
                $(".bootstrap-switch-label").text("排班");
                //获取医生ID
                //$("#d_right_content").load("./nurse_mgr/patient_tmt_info.html");

                try { my_cefsharp.Set_PageKeyFlag_Cef("Patient.nurse"); } catch (err) { }
                window.location.href = '../index.html';
            } else {
                //切换到排版
                console.log("切换到排班");
                try { my_cefsharp.Set_PageKeyFlag_Cef("Patient.nurse"); } catch (err) { }
                $(".bootstrap-switch-label").text("分诊");
                ////加载排版页面
            }
        },
    });

    $("[name='switch_p_or_p']").bootstrapSwitch('state', false);
}


//查询科室2-3级
function queryDeptNodes(jsonData, deptId) {

    var opHtml = "";

    for (var i = 0; i < jsonData.length; i++) {
        var _deptId = jsonData[i].deptId;
        var _deptName = jsonData[i].deptName;
        var _parentId = jsonData[i].parentId;
        var _deptLevel = jsonData[i].deptLevel;

        if (_parentId == deptId) {

            if (_deptLevel == "2") {
                opHtml += "<option style='color:#58DCAD' value='" + _deptId + "'>&nbsp;&nbsp;├ " + _deptName + "</option>";
            }
            else if (_deptLevel == "3") {
                opHtml += "<option  style='color:#4EA3F9' value='" + _deptId + "'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;├ " + _deptName + "</option>";
            }
            var nodeHtml = queryDeptNodes(jsonData, _deptId);
            if (nodeHtml != "") {
                opHtml += nodeHtml;
            }
        }
    }
    return opHtml;
}

function mloadDept(divId) {


    var _triageId = unescape(getCookie("deviceId"));

    $.ajax({
        url: mqueryDeptListUrl,
        type: 'get',
        data:{
            triageId: _triageId
        },
        //async: false,
        success: function (d) {
            if (JSON.parse(d).status == "0") {
                var menuListObj = new Object;
                var deptItems = JSON.parse(d).data;

                var opHtml = "";
                for (var i = 0; i < deptItems.length; i++) {
                    var _deptId = deptItems[i].deptId;
                    var _deptName = deptItems[i].deptName;
                    opHtml += "<option value='" + _deptId + "'>" + _deptName + "</option>";
                }
                $("#" + divId).html(opHtml);
                loadArrangeRuleTableData();
                queryBzpb();
            }
        }
    });
}

function changeOperate(d) {
    m_operType = d;

    if (d == 0) {
        var button_save1 = '<a href="#" onclick="saveArrangeRule();" class="btn btn-success" id="but_save" name="but_save"><i class="glyphicon glyphicon-floppy-disk" ></i> 保存</a>';
        //var button_export = '<a href="#" onclick="exportArrangeRule();" class="btn btn-info" id="but_export" name="but_export"><i class="glyphicon glyphicon-export" ></i> 导出</a>';

        $(".s_operate_bar").html(button_save1);
        $("#span_dept").show();
        $("#span_infoname").hide();
    }
    else if (d == 1) {
        var button_save = '<a href="#" onclick="saveWeekArrangeRule();" class="btn btn-success" id="but_save" name="but_save"><i class="glyphicon glyphicon-floppy-disk" ></i> 保存</a>';
        var button_add = '<a href="#" onclick="addWeekArrangeRule();" class="btn btn-danger" id="but_add" name="but_add" ><i class="glyphicon glyphicon-plus" ></i> 添加</a>';
        //var button_export = '<a href="#" onclick="exportWeekArrangeRule();" class="btn btn-info" id="but_export" name="but_export"><i class="glyphicon glyphicon-export" ></i> 导出</a>';

        $(".s_operate_bar").html(button_save + "&nbsp;&nbsp;&nbsp;" + button_add);
        $("#span_dept").show();
        $("#span_infoname").hide();

        queryBzpb();
        setDate(new Date());

    } else if (d == 2) {
        var button_new = '<a href="#" onclick="newArrangePlayRule();" class="btn btn-warning" id="but_new" name="but_new"><i class="glyphicon glyphicon-pencil" ></i> 新建</a>';
        $(".s_operate_bar").html(button_new);
        $("#span_dept").hide();
        $("#span_infoname").show();

    }
}

//新建显示规则
function newArrangePlayRule() {
    window.location.href = "../arrange/new_displayrule.html";
}

//保存排班规则
function saveArrangeRule() {

    var _len = $("#table_arrange_rule tr").length;
    if (_len == 0)
        return;

    var _doctorObj = new Object;
    var _doctorRuleInfoArr = [];

    $("#table_arrange_rule tr").each(function () {
        var _jsonObj = $(this).prop("id");
        var _week_1 = $(this).find("td:eq(3)").find("select").val() == null ? [0] : $(this).find("td:eq(3)").find("select").val();
        var _week_2 = $(this).find("td:eq(4)").find("select").val() == null ? [0] : $(this).find("td:eq(4)").find("select").val();
        var _week_3 = $(this).find("td:eq(5)").find("select").val() == null ? [0] : $(this).find("td:eq(5)").find("select").val();
        var _week_4 = $(this).find("td:eq(6)").find("select").val() == null ? [0] : $(this).find("td:eq(6)").find("select").val();
        var _week_5 = $(this).find("td:eq(7)").find("select").val() == null ? [0] : $(this).find("td:eq(7)").find("select").val();
        var _week_6 = $(this).find("td:eq(8)").find("select").val() == null ? [0] : $(this).find("td:eq(8)").find("select").val();
        var _week_7 = $(this).find("td:eq(9)").find("select").val() == null ? [0] : $(this).find("td:eq(9)").find("select").val();

        /**
         * 目的就是拼接成 "schedulingKey":"[[1,2,3],[1,2,3,4],[3,4],[1,2],[0],[3,4],[1,2,3,4,5]]"的格式
         */
        var _SchedulingKey = ['[' + _week_1.map(Number) + ']' + "," +  '[' + _week_2.map(Number) + ']' + "," +  '[' + _week_3.map(Number) + ']' + "," +  '[' + _week_4.map(Number) + ']' + "," +  '[' + _week_5.map(Number) + ']' + "," +  '[' + _week_6.map(Number) + ']' + "," +  '[' + _week_7.map(Number) + ']'];
        var _jsonObject = JSON.parse(_jsonObj);

        var _doctorInfo = new Object;
        _doctorInfo.deptId = _jsonObject.deptId;
        _doctorInfo.doctorId = _jsonObject.doctorId;
        _doctorInfo.doctorKey = _jsonObject.doctorKey;
        _doctorInfo.doctorName = _jsonObject.doctorName;
        _doctorInfo.doctorTitle = _jsonObject.doctorTitle;
        _doctorInfo.hospitalId = _jsonObject.hospitalId;
        _doctorInfo.isSpeciallyInvite = _jsonObject.isSpeciallyInvite;
        _doctorInfo.SchedulingKey = JSON.stringify(_SchedulingKey).replace(/\"/g,"");
        _doctorRuleInfoArr.push(_doctorInfo);
    });

    _doctorObj.doctor = _doctorRuleInfoArr;
    //console.log(JSON.stringify(_doctorObj));

    /**
     * 保存医生排班规则接口
     */

    $.ajax({
        url: updateRuleUrl,
        type: 'post',
        beforeSend: function () {
            layer.msg("正在保存", { icon: 16 });
        },
        data: {
            param: JSON.stringify(_doctorObj)
        },
        success: function (d) {
            if (JSON.parse(d).status == "0") {
                loadArrangeRuleTableData();
                layer.alert("保存成功,新的排班规则将立即执行。", { icon: 1 });
            } else {
                layer.alert("保存失败:" + JSON.parse(d).desc, { icon: 2 });
            }
        }
    });
}

//查询
function queryRule() {
    loadArrangeRuleTableData();
    queryBzpb();
}

/**
 * 本周排班-点击添加按钮
 * 添加-选择医生-确定之后，本周排班回显医生信息
 * 加载子窗口回调选中特聘医生信息
 */

function loadOneTpDoctor(d) {
    var _index = null;
    var _selectedArr = d.split("\2");
    for (var i = 0; i < _selectedArr.length; i++) {
        if(_selectedArr[i] == "") continue;
        var _doctorId = _selectedArr[i];

        $.ajax({
            url: queryTpRuleUrl,
            type: 'get',
            beforeSend: function () {
                _index = layer.msg("正在加载数据", { icon: 16 });
            },
            data: {
                doctorId: _doctorId,
                beginDate: _mBeginDate,
                endDate: _mEndDate
            },
            success: function (d) {
                layer.close(_index);
                if (JSON.parse(d).status == 0) {
                    var dataInfo = JSON.parse(d);
                    var _doctorInfo = dataInfo.data[0];

                    var _doctorId = _doctorInfo.doctorId;
                    var _doctorName = _doctorInfo.doctorName;
                    var _doctorKey = _doctorInfo.doctorKey;
                    var _doctorTitle = _doctorInfo.doctorTitle;
                    var _schedulingId = _doctorInfo.schedulingId;
                    var _isSpeciallyInvite = _doctorInfo.isSpeciallyInvite;

                    var _isSpeciallyInviteDesc = _isSpeciallyInvite == "1" ? "特聘" : "非特聘";

                    var _titledesc = _doctorTitle == "1" ? "住院医师" : _doctorTitle == "2" ? "主治医师"
                        : _doctorTitle == "3" ? "副主任医师" : _doctorTitle == "4" ? "主任医师" : "未设置";

                    //遍历所有医生
                    var weekHtml = "<tr id="+ JSON.stringify(dataInfo.data) +">" +
                        "<td><span>" + _doctorKey + "</span></td>" + //工号
                        "<td><span>" + _doctorName + "</span></td>" + //医生
                        "<td><span>" + _isSpeciallyInviteDesc + "</span></td>" + //特聘
                        "<td><span>" + _titledesc + "</span></td>" + //职称
                        getWeekScheduleHtml(dataInfo.data) +
                        "<td><input type='button' class='but_delete' value='删除' onclick='deleteWeekRule(this);'/></td>" +
                        "</tr>";
                    $(weekHtml).appendTo("#t_table_bzpb_content");

                    $('.multipleSelected1').multiselect({
                        nonSelectedText: '休息',
                        buttonWidth: 107,
                        numberDisplayed:'100',//显示个数设置为最大
                        allSelectedText:'' //全选text设置为空，就可以超过四个也显示了
                    });
                    $('.multipleSelected1').multiselect('refresh');

                }
            }
        });
    }

}

//删除本周排班
function deleteWeekRule(t) {
    $(t).parent().parent().remove();
}

//保存本周排班
function saveWeekArrangeRule() {

    var bzRuleObj = new Object;
    var ruleArray = [];
    $("#t_table_bzpb_content tr").each(function () {

        var _doctorInfoArr = new Array();
        var _infoJson = JSON.parse($(this).prop("id"));

        var week_i = 0;
        for (var i = 4; i < 11; i++) {

            var _doctorInfoObj = new Object;
            var _schedulingType = $(this).find("td:eq('" + i + "') select").val() == null ? [0] : $(this).find("td:eq('" + i + "') select").val();

            _doctorInfoObj.deptId = _infoJson[0].deptId;
            _doctorInfoObj.deptName = _infoJson[0].deptName;
            _doctorInfoObj.doctorId = _infoJson[0].doctorId;
            _doctorInfoObj.doctorKey = _infoJson[0].doctorKey;
            _doctorInfoObj.doctorName = _infoJson[0].doctorName;
            _doctorInfoObj.doctorTitle = _infoJson[0].doctorTitle;
            _doctorInfoObj.isSpeciallyInvite = _infoJson[0].isSpeciallyInvite;
            _doctorInfoObj.schedulingDate = _infoJson[week_i].schedulingDate;

            // console.log(_infoJson[week_i].schedulingDate);
            _doctorInfoObj.week = _infoJson[week_i].week;
            _doctorInfoObj.schedulingType = _schedulingType;
            _doctorInfoArr.push(_doctorInfoObj);

            week_i++;
        }

        ruleArray.push(_doctorInfoArr);
    });

    bzRuleObj.obj = ruleArray;
    bzRuleObj.beginDate = _mBeginDate;
    bzRuleObj.endDate = _mEndDate;
    bzRuleObj.deptId = $("#dept_infolist").val();

    var indexAlert = null;

    $.ajax({
        url: saveBzPbRuleUrl,
        data: {
            param: JSON.stringify(bzRuleObj)
        },
        type: 'post',
        beforeSend: function () {

            indexAlert = layer.open({
                title: false,
                closeBtn: 0,
                btn: [],
                content: '正在保存',
                icon: 16
            });
        },
        success: function (d) {
            // console.log(d);

            layer.close(indexAlert);
            if (JSON.parse(d).status == '0') {
                layer.confirm('保存成功', {
                    icon: 1,
                    btn: ['确定'] //按钮
                }, function () {
                    queryBzpb(_mBeginDate, _mEndDate);
                });

            } else {
                layer.alert("保存失败：" + JSON.parse(d).desc, { icon: 2 });
            }
        }
    });
    // console.log(JSON.stringify(bzRuleObj));
}

//新建本周排班
function addWeekArrangeRule() {

    var _inWeekDoctors = "";
    $("#t_table_bzpb_content tr").each(function () {
        _inWeekDoctors += $(this).find("td:eq(1)").prop("id") + "\5";
    });

    var _url = '../arrange/select_doctor.html?dept=' + window.encodeURIComponent(encodeURI($("#dept_infolist").val()));
    var valstr = _mBeginDate + "\2" + _mEndDate + "\2" + _inWeekDoctors.substr(0, _inWeekDoctors.length - 1);

    setCookie($("#dept_infolist").val(), valstr);
    layer.open({
        type: 2,//加载外部页面类型
        closeBtn: 1,
        title: "选择医生",//不显示标题栏
        // shadeClose: true,//点其他地方自动关闭
        area: ['800px', '500px'],
        content: _url,
    });

}

function GetSchedulStatusCss(d) {

    if (d == "0") {
        return "#D6D7D9";
    } else if (d == "1") {
        return "#BADFF9";
    } else if (d == "2") {
        return "#F3FAB7";
    } else if (d == "3") {
        return "#B8F7E2";
    } else if (d == "4") {
        return "#EA9DCB";
    } else if (d == "5") {
        return "#67B3ED";
    }

}

function GetSchedulStatusCss_1(_this) {

    var d = $(_this).val();

    if (d == "0") {
        $(_this).css({ "background-color": "#D6D7D9" });
    } else if (d == "1") {
        $(_this).css({ "background-color": "#BADFF9" });
    } else if (d == "2") {
        $(_this).css({ "background-color": "#F3FAB7" });
    } else if (d == "3") {
        $(_this).css({ "background-color": "#B8F7E2" });
    } else if (d == "4") {
        $(_this).css({ "background-color": "#EA9DCB" });
    } else if (d == "5") {
        $(_this).css({ "background-color": "#67B3ED" });
    }

}

function ConvertWeek(w) {
    if (w == "1")
        return "一";
    else if (w == "2")
        return "二";
    else if (w == "3")
        return "三";
    else if (w == "4")
        return "四";
    else if (w == "5")
        return "五";
    else if (w == "6")
        return "六";
    else if (w == "7")
        return "日";
}

function ConvertDate(d) {
    return d.split("-")[0] + "年" + "-" + d.split("-")[1] + "月" + "-" + d.split("-")[2] + "日";
}

//切换到设置密码
function linkEditPwd() {
    window.location.href = "../setting/edit_pwd.html";
}

/**
 * ===== 排班字典 =====
 */

/**
 * 排班字典
 * 接口获取排班data数据schedulingdicList
 */
function schedulingDictionary() {
    $.ajax({
        url:schedulingdicListUrl,
        type:"get",
        async:false,
        data:{
            dicType:1
        },
        success:function (d) {
            var dataType = JSON.parse(d);
            // var dataType = schedulingdicList;
            if(dataType.status == "0"){
                schedulingdicList = dataType.data;
                console.log("排班字典返回值====>>>");
                console.log(schedulingdicList);
            }else{
                layer.alert(dataType.desc,{icon:2});
            }
        }
    });
}
